<template>
  <div class="bg-white h-4 dark:bg-zinc-900 sticky top-0 left-0 z-10">
    <ul
      ref="ulTarget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] top-0.5 bg-zinc-900 rounded-lg duration-200"
      ></li>
      <!-- 汉堡按钮 -->
      <li
       
        class="fixed top-0 right-[-1px] dark:bg-zinc-900 h-3.5 px-1 flex items-center bg-white z-20 shadow-l-white dark:shadow-l-zinc"
        @click="onShowPopup"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>

        <!-- items -->
      </li>
      <li
        v-for="(item, index) in data"
        :key="item.id"
        @click="onItemClick(index)"
        :ref="setItemRef"
        class="shrink-0 px-1.5 text-xs py-0 z-10 duration-200 last:mr-4"
        :class="{
          'text-zinc-100': currentCategoryIndex === index
        }"
      >
        {{ item.name }}
      </li>
    </ul>
    <m-popup v-model="isVisiable">
      <menu-vue :categorys="data" @onItemClick="onItemClick"></menu-vue>
     </m-popup>
  </div>
</template>
<script setup>
import { ref, onBeforeUpdate, watch } from "vue";
import { useScroll } from "@vueuse/core";
import MenuVue from '@/views/main/components/menu/index.vue'
defineProps({
  data: {
    type: Array,
    required: true
  }
});
// 滑块
const sliderStyle = ref({
  transform: "translateX(0px)",
  width: "52px"
});


//选中 item 下标
const currentCategoryIndex = ref(0);

// 获取所有的item 元素
let itemRefs = [];
const setItemRef = (el) => {
  if (el) itemRefs.push(el);
};

//数据改变之后 DOM变化之前
onBeforeUpdate(() => {
  itemRefs = [];
});

// 获取ul 元素
const ulTarget = ref(null);
//通过vueuse => useScroll 获取响应式的scroll 滚动距离
const { x: ulScrollLeft } = useScroll(ulTarget);

//watch监听
watch(currentCategoryIndex, (val) => {
  const { left, width } = itemRefs[val].getBoundingClientRect();
  sliderStyle.value = {
    //滑块的位置 = ul 横向滚动的位置 + 当前元素的left - ul的padding
    transform: `translateX(${ulScrollLeft.value + left - 10}px)`,
    width: width + "px"
  };
  if(isVisiable.value){
    ulTarget.value.scrollLeft = left + ulTarget.value.scrollLeft
    isVisiable.value = false
  }
   

});

//点击事件
const onItemClick = (index) => {
  currentCategoryIndex.value = index;
};

// 控制popup展示
const isVisiable = ref(false)
const onShowPopup = () => {
  isVisiable.value = true
}
</script>
